<?php
/**
 * @author      Alex Bilbie <hello@alexbilbie.com>
 * @copyright   Copyright (c) Alex Bilbie
 * @license     http://mit-license.org/
 *
 * @link        https://github.com/thephpleague/oauth2-server
 */

namespace app\components\oauth2\repositories;

use app\components\oauth2\entities\ClientEntity;
use app\models\Admin;
use app\models\OauthClient;
use app\models\User;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Repositories\UserRepositoryInterface;

class UserRepository implements UserRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function getUserEntityByUserCredentials(
        $username,
        $password,
        $grantType,
        ClientEntityInterface $clientEntity
    )
    {
        $error = '';

        if ($clientEntity instanceof ClientEntity) {
            $oauthClient = $clientEntity->getModel();
            if ($oauthClient->client_user_type == OauthClient::TYPE_BACKGROUND) {
                $data['username'] = $username;
                $data['password'] = $password;

                $model = new Admin();
                $model->setScenario(Admin::SCENARIO_LOGIN);
                if ($model->load($data, '') && $model->validate()) {
                    //更新登录时间
                    $admin = Admin::find()
                        ->where([
                            'username' => $model['username'],
                            'password' => $model['password'],
                        ])
                        ->one();
                    \Yii::$app->user->login($admin);
                    return $admin;
                }

                $error = current($model->getFirstErrors());
            }elseif($oauthClient->client_user_type == OauthClient::TYPE_FRONTAND){
                $data['username'] = $username;
                $data['password'] = $password;

                $model = new User();
                $model->setScenario(User::SCENARIO_LOGIN);
                if ($model->load($data, '') && $model->validate()) {
                    //更新登录时间
                    $user = User::find()
                        ->where([
                            'username' => $model['username'],
                            'password' => $model['password'],
                        ])
                        ->one();
                    \Yii::$app->user->login($user);
                    return $user;
                }

                $error = current($model->getFirstErrors());
            }
        }

        throw OAuthServerException::invalidGrant($error);

        return;
    }
}